package cn.wlinker.driver.coap.core;

import org.eclipse.californium.core.CoapResource;
import org.eclipse.californium.core.coap.CoAP;
import org.eclipse.californium.core.server.resources.CoapExchange;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class MqttController extends CoapResource {
    public MqttController(String name) {
        super(name);
    }

    @Override
    public void handleGET(CoapExchange exchange) {
        List<String> uriQuery = exchange.getRequestOptions().getUriQuery();
        System.out.println("Get Mqtt parameters: " + uriQuery);
        if (uriQuery !=null && uriQuery.size()>0) {
            for (String s : uriQuery) {
                String[] split = s.split("=");
                System.out.println(String.format("k= %s,v=%s", split[0], split[1]));
            }
        }
        System.out.println(String.format("Get mqtt request <<<  %s,%s",
                uriQuery,
                new Date()
        ));
        exchange.respond(CoAP.ResponseCode.CONTENT, String.format("Get mqtt !, <<< %s >>> ", uriQuery));
    }

    @Override
    public void handlePOST(CoapExchange exchange) {
        List<String> uriQuery = exchange.getRequestOptions().getUriQuery();
        System.out.println("Post Mqtt parameters: " + uriQuery);
        if (uriQuery !=null && uriQuery.size()>0) {
            for (String s : uriQuery) {
                String[] split = s.split("=");
                System.out.println(String.format("k= %s,v=%s", split[0], split[1]));
            }
        }
        String requestText = exchange.getRequestText();
        byte[] requestPayload = exchange.getRequestPayload();
        System.out.println(String.format("Post mqtt request <<<  %s,%s ,cbor Arr=%s",
                requestText,
                new Date(),
                Arrays.toString(requestPayload)
        ));
        exchange.respond(CoAP.ResponseCode.CONTENT, String.format("Post mqtt !, <<< %s >>> ", requestText));
    }
}
